<script setup lang="ts">
import { defineProps, toRefs, onMounted, onUnmounted, shallowRef, watch, withDefaults } from "vue"
import APlayer from "aplayer"
import "aplayer/dist/APlayer.min.css"

const aplayer = shallowRef<HTMLElement>()

const props = withDefaults(
  defineProps<{
    id?: string
    src?: string
    name?: string
    author?: string
    img?: string
    lrc?: string
  }>(),
  {
    id: "2085709355",
  }
)

const { id, src, name, author, img, lrc } = toRefs(props)
let instance: any = null

const init = () => {
  unMount()
  const theme = getComputedStyle(document.documentElement).getPropertyValue("--themeColor")
  if (id!.value) {
    //网易云id模式
    const url = `https://api.i-meto.com/meting/api?server=netease&type=song&id=${
      id!.value
    }&r=${Math.random()}`
    fetch(url)
      .then(res => res.json())
      .then(data => {
        const song = data[0]
        instance = new APlayer({
          container: aplayer.value,
          theme: theme,
          loop: "loop",
          lrcType: 3,
          audio: [
            {
              name: name!.value ? name!.value : song.title,
              artist: author!.value ? author!.value : song.author,
              url: src!.value ? src!.value : song.url,
              cover: img!.value ? img!.value : song.pic,
              lrc: lrc!.value ? lrc!.value : song.lrc,
            },
          ],
        })
      })
  } else {
    //自给模式
    instance = new APlayer({
      container: aplayer.value,
      theme: theme,
      loop: "loop",
      lrcType: 3,
      audio: [
        {
          name: name!.value,
          url: src!.value,
          artist: author!.value,
          cover: img!.value,
          lrc: lrc!.value,
        },
      ],
    })
  }
}
const unMount = () => {
  if (instance) {
    console.log("unMount")
    instance.destroy()
  }
}
watch(props, init)
onUnmounted(unMount)
onMounted(init)
</script>

<template>
  <div class="aplayer" ref="aplayer"></div>
</template>

<style lang="scss" scoped>
.aplayer {
  margin-bottom: var(--bottom);
  white-space: normal !important;
}
.aplayer:deep(.aplayer-title) {
  color: #333;
}
</style>
